package CompletableFuturefd;


import com.google.common.collect.Lists;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

public class ListBatch {

    private static final ExecutorService executor = Executors.newFixedThreadPool(10);


    public static List<Integer> add() {
         List<Integer> list = new ArrayList<>();

        for (int i = 1; i <= 100; i++) {
            list.add(i);
        }
        return list;
    }

    public static void main(String[] args) {
        List<Integer> list = add();//每10个一组

        List<CompletableFuture<Integer>> completableFutures = Lists.partition(list, 15)
                .stream()
                .map(batchList -> CompletableFuture.supplyAsync(() -> {
                    System.out.println(batchList);
                    return 1;
                },executor)).collect(Collectors.toList());

        System.out.println(completableFutures.size() + "=====");
        System.out.println("上面所有分组执行完成");

        try {
            //这里是返回7个CompletableFuture
            CompletableFuture.allOf(completableFutures.toArray(new CompletableFuture[0])).get();
            System.out.println("===allOf嘻嘻==");
            Integer[] sum = {0};
            completableFutures.stream().forEach(future -> {
                sum[0] += future.join();
            });
            System.out.println(sum[0]);//所以：结果为7
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }
}
